﻿<h3>TestBootstrapChartLine</h3>
<Chart @ref="_lineChart" OnInitAsync="() => OnInit(0.4f, false)"  Height="300px"/>
@code {
    private readonly Random _randomer = new();
    private Chart _lineChart = default!;
    private int _lineDatasetCount = 2;
    private int _lineDataCount = 7;    
    System.Timers.Timer _timer;//定时触发

    protected override void OnInitialized()
    {
        //初始化定时器
        _timer = new System.Timers.Timer(10000);//间隔10s
        _timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
        _timer.Start();
    }


    private async Task<ChartDataSource> OnInit(float tension, bool hasNull)
    {
        var ds = new ChartDataSource();
        ds.Options.Title = "Line Chart";
        ds.Options.LegendLabelsFontSize = 16;
        ds.Options.X.Title = "days";
        ds.Options.Y.Title = "Numerical value";
        ds.Options.XScalesBorderColor = "red";
        ds.Options.YScalesBorderColor = "red";

        ds.Options.XScalesGridColor = "blue";
        ds.Options.XScalesGridTickColor = "blue";
        ds.Options.XScalesGridBorderColor = "blue";

        ds.Options.YScalesGridColor = "blue";
        ds.Options.YScalesGridTickColor = "blue";
        ds.Options.YScalesGridBorderColor = "blue";

        ds.Labels = Enumerable.Range(1, _lineDataCount).Select(i => i.ToString());
        for (var index = 0; index < _lineDatasetCount; index++)
        {
            ds.Data.Add(new ChartDataset()
            {
                BorderWidth = _randomer.Next(1, 5),
                Tension = tension,
                Label = $"Set {index}",
                Data = Enumerable.Range(1, _lineDataCount).Select((i, index) => (index == 2 && hasNull) ? null! : (object)_randomer.Next(20, 37)),
                PointRadius = 5,
                PointHoverRadius = 10
            });
        }

        // 模拟异步
        await Task.Delay(100);
        return ds;
    }

    //定时更新数据
    public void OnTimerCallback()
    {
        _ = InvokeAsync(() =>
        {
            _lineChart.Update(ChartAction.Update);
            StateHasChanged();
        });
    }
}
